<!-- V-webapp/src/views/ProfileView.vue -->
<template>
  <div class="profile-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 用户信息头部 -->
    <div v-else class="user-header">
      <div class="user-avatar">
        <el-avatar :size="80" :src="userInfo.avatar" class="avatar">
          {{ userInfo.name?.charAt(0) || '?' }}
        </el-avatar>
      </div>
      <div class="user-info">
        <h2 class="user-name">{{ userInfo.name || '未登录' }}</h2>
        <p class="user-id">ID: {{ userInfo.id || '--' }}</p>
        <p class="user-email">{{ userInfo.email || '请登录' }}</p>
        <p v-if="isLoggedIn && !userInfo.name" class="loading-text" style="font-size: 12px; color: #666;">
          正在加载用户信息...
        </p>
      </div>
      <el-button 
        v-if="!isLoggedIn" 
        type="primary" 
        @click="$router.push('/login')"
        class="login-btn"
      >
        立即登录
      </el-button>
      <el-button 
        v-else 
        type="primary" 
        link
        @click="handleLogout"
        class="logout-btn"
      >
        退出登录
      </el-button>
    </div>

    <!-- 数据统计 -->
    <div v-if="isLoggedIn" class="stats-grid">
      <div class="stat-item">
        <div class="stat-number">{{ stats.myRegistrations || 0 }}</div>
        <div class="stat-label">我的预约</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ stats.myOrders || 0 }}</div>
        <div class="stat-label">我的订单</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ stats.myCart || 0 }}</div>
        <div class="stat-label">购物车</div>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div v-if="isLoggedIn" class="menu-sections">
      <!-- 我的活动 -->
      <div class="menu-section">
        <h3 class="section-title">我的活动</h3>
        <div class="menu-grid">
          <div class="menu-item" @click="goToMyRegistrations">
            <div class="menu-icon">
              <el-icon><Calendar /></el-icon>
            </div>
            <span class="menu-text">活动预约</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
          
          <div class="menu-item" @click="goToMyFavorites">
            <div class="menu-icon">
              <el-icon><Star /></el-icon>
            </div>
            <span class="menu-text">我的收藏</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>
      </div>

      <!-- 我的订单 -->
      <div class="menu-section">
        <h3 class="section-title">我的订单</h3>
        <div class="menu-grid">
          <div class="menu-item" @click="goToMyOrders">
            <div class="menu-icon">
              <el-icon><Document /></el-icon>
            </div>
            <span class="menu-text">全部订单</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
          
          <div class="menu-item" @click="goToPendingOrders">
            <div class="menu-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <span class="menu-text">待支付</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>
      </div>

      <!-- 账户设置 -->
      <div class="menu-section">
        <h3 class="section-title">账户设置</h3>
        <div class="menu-grid">
          <div class="menu-item" @click="goToSettings">
            <div class="menu-icon">
              <el-icon><Setting /></el-icon>
            </div>
            <span class="menu-text">个人设置</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
          
          <div class="menu-item" @click="goToAbout">
            <div class="menu-icon">
              <el-icon><InfoFilled /></el-icon>
            </div>
            <span class="menu-text">关于我们</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作 -->
    <div v-if="isLoggedIn" class="bottom-actions">
      <el-button 
        type="danger" 
        @click="handleClearData"
        class="clear-btn"
        link
      >
        清除缓存数据
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Calendar, 
  Star, 
  Document, 
  Clock, 
  Setting, 
  InfoFilled,
  ArrowRight 
} from '@element-plus/icons-vue'
import { getUserInfo, logout, getCurrentUser } from '@/api/auth'

interface UserInfo {
  id?: number
  name?: string
  email?: string
  avatar?: string
  type?: string
}

interface UserStats {
  myRegistrations: number
  myOrders: number
  myCart: number
}

const router = useRouter()
const userInfo = ref<UserInfo>({})
const stats = ref<UserStats>({
  myRegistrations: 0,
  myOrders: 0,
  myCart: 0
})
const loading = ref(false)

// 计算登录状态
const isLoggedIn = computed(() => {
  const token = localStorage.getItem('token')
  console.log('🔐 个人中心 - 登录状态检查:', token ? '已登录' : '未登录')
  return !!token
})

// 获取用户信息 - 完全重写，修复API调用问题
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    console.log('🔐 获取用户信息 - Token状态:', token ? '已登录' : '未登录')
    
    if (!token) {
      userInfo.value = {}
      console.log('❌ 没有token，显示未登录状态')
      return
    }
    
    loading.value = true
    console.log('📡 开始获取用户信息...')

    // 方法1：先尝试从本地存储获取用户信息
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      try {
        const parsedInfo = JSON.parse(storedUserInfo)
        userInfo.value = parsedInfo
        console.log('💾 从本地存储加载用户信息:', userInfo.value)
      } catch (e) {
        console.warn('❌ 本地存储的用户信息格式错误')
        localStorage.removeItem('userInfo')
      }
    }

    // 方法2：尝试调用用户信息API
    try {
      console.log('🔄 调用用户信息API: /auth/user-info')
      const response = await getUserInfo()
      console.log('✅ 用户信息API响应:', response)
      
      // 根据你的API响应结构调整
      if (response && (response.success || response.code === 200)) {
        // 不同可能的响应结构
        const userData = response.data?.user || response.data || response.user
        if (userData) {
          userInfo.value = {
            id: userData.id || userData.audience_id || userData.anchor_id,
            name: userData.name || userData.audience_name || userData.anchor_name,
            email: userData.email,
            avatar: userData.avatar,
            type: userData.type || userData.userType
          }
          console.log('👤 成功设置用户信息:', userInfo.value)
          
          // 保存到本地存储
          localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        } else {
          console.warn('⚠️ API响应中没有用户数据:', response)
        }
      } else {
        console.warn('⚠️ API响应格式不正确:', response)
      }
    } catch (apiError: any) {
      console.error('❌ 用户信息API调用失败:', apiError)
      
      // 如果API调用失败，尝试使用 /auth/me 接口
      try {
        console.log('🔄 尝试备用接口: /auth/me')
        const meResponse = await getCurrentUser()
        console.log('✅ 备用接口响应:', meResponse)
        
        if (meResponse && (meResponse.success || meResponse.code === 200)) {
          const userData = meResponse.data?.user || meResponse.data || meResponse.user
          if (userData) {
            userInfo.value = {
              id: userData.id || userData.audience_id || userData.anchor_id,
              name: userData.name || userData.audience_name || userData.anchor_name,
              email: userData.email,
              avatar: userData.avatar,
              type: userData.type || userData.userType
            }
            console.log('👤 通过备用接口设置用户信息:', userInfo.value)
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
          }
        }
      } catch (meError) {
        console.error('❌ 备用接口也失败:', meError)
        
        // 如果两个API都失败，使用模拟数据
        if (!userInfo.value.name) {
          userInfo.value = {
            id: Date.now(),
            name: '用户' + Math.floor(Math.random() * 10000),
            email: 'user@example.com',
            avatar: '',
            type: 'audience'
          }
          console.log('🛠️ 使用模拟用户信息:', userInfo.value)
          localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        }
      }
    }
    
    // 临时模拟统计信息
    stats.value = {
      myRegistrations: Math.floor(Math.random() * 5),
      myOrders: Math.floor(Math.random() * 3),
      myCart: Math.floor(Math.random() * 2)
    }
    
  } catch (error) {
    console.error('❌ 获取用户信息总体失败:', error)
    userInfo.value = {}
  } finally {
    loading.value = false
  }
}

// 处理退出登录 - 修复错误处理
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      type: 'warning'
    })
    
    console.log('🚪 开始退出登录...')
    
    try {
      // 尝试调用退出API
      await logout()
      console.log('✅ 退出API调用成功')
    } catch (logoutError: any) {
      console.warn('⚠️ 退出API调用失败，继续本地退出:', logoutError.message)
      // 即使API调用失败，也继续本地退出流程
    }
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    userInfo.value = {}
    stats.value = {
      myRegistrations: 0,
      myOrders: 0,
      myCart: 0
    }
    
    console.log('✅ 本地退出完成')
    ElMessage.success('退出成功')
    router.push('/login')
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('❌ 退出失败:', error)
      ElMessage.error('退出失败')
    }
  }
}

// 导航函数
const goToMyRegistrations = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/my-registrations')
}

const goToMyFavorites = () => {
  ElMessage.info('我的收藏功能开发中')
}

const goToMyOrders = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/my-orders')
}

const goToPendingOrders = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/my-orders?status=pending')
}

const goToSettings = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  router.push('/settings')
}

const goToAbout = () => {
  ElMessage.info('关于我们页面开发中')
}

// 处理清除缓存
const handleClearData = async () => {
  try {
    await ElMessageBox.confirm('确定要清除所有缓存数据吗？', '提示', {
      type: 'warning'
    })
    
    // 清除本地存储
    localStorage.clear()
    sessionStorage.clear()
    
    ElMessage.success('清除成功')
    // 重新加载页面
    window.location.reload()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('清除失败')
    }
  }
}

onMounted(() => {
  console.log('📱 个人中心页面加载')
  fetchUserInfo()
})
</script>

<style scoped>
/* 你的原有CSS保持不变 */
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 16px;
}

.user-header {
  display: flex;
  align-items: center;
  gap: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-avatar .avatar {
  border: 3px solid #667eea;
}

.user-info {
  flex: 1;
}

.user-name {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.user-id {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #666;
}

.user-email {
  margin: 0;
  font-size: 14px;
  color: #999;
}

.login-btn, .logout-btn {
  border-radius: 20px;
  font-weight: 600;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.stat-item {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.menu-sections {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.menu-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.menu-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
}

.menu-item:hover {
  background: rgba(102, 126, 234, 0.1);
  transform: translateX(4px);
}

.menu-item:not(:last-child) {
  border-bottom: 1px solid #f5f5f5;
}

.menu-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 8px;
  color: white;
}

.menu-text {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.bottom-actions {
  text-align: center;
  margin-top: 20px;
}

.clear-btn {
  color: #ff4757;
  font-size: 14px;
}

.loading-container {
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  margin-bottom: 20px;
}
</style>